package com.leetcode.no142;


class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
        next = null;
    }
}

public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode fast, slow;
        fast = slow = head;

        boolean hasCyc = false;

        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
                hasCyc = true;
                break;
            }
        }
        if (!hasCyc) {
            return null;
        }

        fast = head;

        // 快慢指针再走x步相遇
        while (fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;


    }
}
